from django.shortcuts import render
from django.db import DatabaseError
from django.views import View
from django import http
import json
from space.models import Space, JoinSpace, ShareSpace
from user.models import User
from essay.models import Essay, Like, Comment, Collect
import datetime


# 创建空间接口
class CreateSpace(View):

    def post(self, request):
        space_name = json.loads(request.body)['spaceName']
        space_image = json.loads(request.body)['spaceImage']
        phone = json.loads(request.body)['phone']
        space_description = json.loads(request.body)['spaceDescription']
        space_bright = json.loads(request.body)['spaceBright']
        try:
            Space.objects.create(space_name=space_name, space_image=space_image, phone=phone,
                            space_description=space_description, space_light_description=space_bright['text'],
                            space_light_image=space_bright['image'])
        except DatabaseError:
            return http.JsonResponse({'code': '205', 'message': '创建失败'})
        return http.JsonResponse({'code': '200', 'message': '创建成功'})


# 返回所有空间信息接口
class GetAllSpace(View):

    def get(self, request):
        space_data = Space.objects.values()
        for item in space_data:
            user_data = list(User.objects.values().filter(phone=item['phone']))
            item['username'] = user_data[0]['username']
            item['create_day'] = (datetime.datetime.now() - item['create_time'].replace(tzinfo=None)).days + 1
        return http.JsonResponse({'code': '200', 'message': '查询成功', 'data': list(space_data)})


# 返回单个空间信息接口
class GetOneSpace(View):

    def get(self, request):
        space_id = request.GET.get('spaceId')
        space_data = list(Space.objects.values().filter(space_id=space_id))
        if space_data:
            user_data = list(User.objects.values().filter(phone=space_data[0]['phone']))
            space_data[0]['username'] = user_data[0]['username']
            space_data[0]['create_day'] = (datetime.datetime.now() - space_data[0]['create_time'].replace(tzinfo=None)).days + 1
            space_data[0]['space_light_image'] = space_data[0]['space_light_image'].split("@")
            if space_data[0]['space_light_image'][0] == '':
                space_data[0]['space_light_image'] = []
            return http.JsonResponse({'code': '200', 'message': '查询成功', 'data': space_data[0]})
        else:
            return http.JsonResponse({'code': '208', 'message': '空间不存在'})


# 获取指定用户已加入的空间
class GetUserJoinSpace(View):

    def get(self, request):
        phone = request.GET.get('phone')
        res_data = JoinSpace.objects.values().filter(phone=phone)
        for item in res_data:
            space_data = Space.objects.values().filter(space_id=item['space_id'])
            item['space_name'] = list(space_data)[0]['space_name']
        return http.JsonResponse({'code': '200', 'message': '查询成功', 'data': list(res_data)})


# 获取用户已创建的空间
class GetUserCreateSpace(View):

    def get(self, request):
        phone = request.GET.get('phone')
        res_data = Space.objects.values().filter(phone=phone)
        return http.JsonResponse({'code': '200', 'message': '查询成功', 'data': list(res_data)})


# 加入空间接口
class UserJoinSpace(View):

    def post(self, request):
        space_id = json.loads(request.body)['space_id']
        phone = json.loads(request.body)['phone']
        join_data = JoinSpace.objects.values().filter(space_id=space_id, phone=phone)
        if join_data:
            return http.JsonResponse({'code': '210', 'message': '已加入过该空间'})
        else:
            space_data = list(Space.objects.values().filter(space_id=space_id))[0]
            if space_data['phone'] == phone:
                return http.JsonResponse({'code': '211', 'message': '不能加入自己创建的空间'})
            else:
                JoinSpace.objects.create(space_id=space_id, phone=phone)
                JoinSpace.addSpacePeople(space_id)
                return http.JsonResponse({'code': '200', 'message': '加入成功'})


# 退出空间接口
class UserExitSpace(View):

    def post(self, request):
        space_id = json.loads(request.body)['space_id']
        phone = json.loads(request.body)['phone']
        JoinSpace.objects.filter(space_id=space_id, phone=phone).delete()
        JoinSpace.reduceSpacePeople(space_id)
        return http.JsonResponse({'code': '200', 'message': '退出成功'})


# 根据用户id查询用户创建和加入的空间
class GetUserSpace(View):

    def get(self, request):
        user_id = request.GET.get('user_id')
        phone = list(User.objects.values().filter(user_id=user_id))[0]['phone']
        create_space_data = list(Space.objects.values().filter(phone=phone))
        user_data = list(User.objects.values().filter(phone=phone))
        for item in create_space_data:
            item['username'] = user_data[0]['username']
            item['create_day'] = (datetime.datetime.now() - item['create_time'].replace(tzinfo=None)).days
        join_space_id = list(JoinSpace.objects.values().filter(phone=phone))
        join_space_data = []
        for item in join_space_id:
            space_data = list(Space.objects.values().filter(space_id=item["space_id"]))[0]
            user_data = list(User.objects.values().filter(phone=space_data['phone']))
            space_data['username'] = user_data[0]['username']
            space_data['create_day'] = (datetime.datetime.now() - space_data['create_time'].replace(tzinfo=None)).days
            join_space_data.append(space_data)
        return http.JsonResponse({'code': '200', 'message': '成功', 'data': {'join_space': join_space_data, 'create_space': create_space_data}})


# 更新空间信息
class UpdateSpaceMessage(View):

    def post(self, request):
        space_name = json.loads(request.body)['space_name']
        space_image = json.loads(request.body)['space_image']
        space_id = json.loads(request.body)['space_id']
        space_description = json.loads(request.body)['space_description']
        space_bright = json.loads(request.body)['spaceBright']
        Space.objects.filter(space_id=space_id).update(space_name=space_name, space_image=space_image, space_description=space_description
                                                       , space_light_description=space_bright['text'], space_light_image=space_bright['image'])
        return http.JsonResponse({'code': '200', 'message': '更新成功'})


# 删除空间
class DeleteSpace(View):

    def get(self, request):
        space_id = request.GET.get('space_id')
        Space.objects.filter(space_id=space_id).delete()
        JoinSpace.objects.filter(space_id=space_id).delete()
        essay_data = list(Essay.objects.values().filter(space_id=space_id))
        for essay in essay_data:
            Essay.objects.filter(essay_id=essay['essay_id']).delete()
            Like.objects.filter(essay_id=essay['essay_id']).delete()
            Comment.objects.filter(essay_id=essay['essay_id']).delete()
            Collect.objects.filter(essay_id=essay['essay_id']).delete()
        return http.JsonResponse({'code': '200', 'message': '删除成功'})


# 获取空间内所有用户信息
class GetSpaceUser(View):

    def get(self, request):
        space_id = request.GET.get('space_id')
        result_data = []
        join_space_data = list(JoinSpace.objects.values().filter(space_id=space_id))
        for join_data in join_space_data:
            user_data = list(User.objects.values().filter(phone=join_data['phone']))[0]
            result_data.append({
                'username': user_data['username'],
                'avatar': user_data['avatar'],
                'sex': user_data['sex'],
                'sign': user_data['sign'],
                **join_data,
                'join_time': join_data['join_time'].strftime("%Y-%m-%d  %H:%M")
            })
        return http.JsonResponse({'code': '200', 'message': '成功', 'data': {'space_user': result_data}})


# 分享空间接口
class UserShareSpace(View):

    def post(self, request):
        space_id = json.loads(request.body)['space_id']
        user_id = json.loads(request.body)['user_id']
        share_code = json.loads(request.body)['share_code']
        share_data = ShareSpace.objects.values().filter(space_id=space_id, user_id=user_id)
        if share_data:
            ShareSpace.objects.filter(space_id=space_id, user_id=user_id).update(share_code=share_code)
        else:
            ShareSpace.objects.create(space_id=space_id, user_id=user_id, share_code=share_code)

        return http.JsonResponse({'code': '200', 'message': '成功'})


# 检查分享链接
class CheckShareSpace(View):

    def post(self, request):
        space_id = json.loads(request.body)['space_id']
        share_code = json.loads(request.body)['share_code']
        share_data = ShareSpace.objects.values().filter(space_id=space_id, share_code=share_code)
        if share_data:
            try:
                space_data = list(Space.objects.values().filter(space_id=space_id))[0]
            except Exception:
                return http.JsonResponse({'code': '208', 'message': '空间不存在'})
            else:
                user_data = list(User.objects.values().filter(phone=space_data['phone']))[0]
                return http.JsonResponse({'code': '200', 'message': '成功', 'spaceData': {**space_data, 'username': user_data['username'], 'avatar': user_data['avatar']}})
        else:
            return http.JsonResponse({'code': '209', 'message': '分享链接已失效'})

